package com.ljm.boot.helloword.letCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test438 {

    public static List<Integer> findAnagrams(String s, String p) {
        int lengths = s.length();
        int lengthp = p.length();
        if(lengths<lengthp){
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        char[] chars = p.toCharArray();
        Arrays.sort(chars);

        for(int i=0;i< s.length()-lengthp+1;i++){
            char[] ss = s.substring(i,i+lengthp).toCharArray();
            Arrays.sort(ss);
            if(Arrays.equals(ss,chars)){
                list.add(i);
            }
        }
        return list;
    }



    public static List<Integer> findAnagrams3(String s, String p) {
        int sLen = s.length(), pLen = p.length();

        if (sLen < pLen) {
            return new ArrayList<Integer>();
        }
        List<Integer> ans = new ArrayList<Integer>();
        int[] sCount = new int[sLen];
        int[] pCount = new int[sLen];
        for (int i = 0; i < pLen; ++i) {
            //根据属性正态分布
            ++sCount[s.charAt(i) - 'a'];
            ++pCount[p.charAt(i) - 'a'];
        }
        if (Arrays.equals(sCount, pCount)) {
            ans.add(0);
        }
        for (int i = 0; i < sLen - pLen; ++i) {
            int next = i + pLen;
            char char1 = s.charAt(i);
            char char2 = s.charAt(next);
            --sCount[char1 - 'a'];//其实位置开始消除
            ++sCount[char2 - 'a'];//末尾位置开始增加，0-3,1-4,2-5
            if (Arrays.equals(sCount, pCount)) {
                ans.add(i + 1);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        String s = "cbaebabacd", p = "abc";
        findAnagrams3(s,p);
    }
}
